<?php
/*
CREATE TABLE IF NOT EXISTS `article` (
  `itemid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(100) NOT NULL,
  `content` text NOT NULL,
  PRIMARY KEY (`itemid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
*/
//https://www.cnblogs.com/mracale/p/10774047.html
//https://www.cnblogs.com/lishuaige/articles/5545921.html
//https://www.cnblogs.com/fuhai0815/p/9792520.html
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header("Access-Control-Allow-Credentials: true");





header("content-type:application/json;charset=utf-8");
error_reporting(E_ALL);
ini_set('display_errors',1);
set_time_limit(0);
date_default_timezone_set('Asia/Shanghai');

function todata($code=0,$msg='success',$data=[]){
	return ['code'=>$code,'msg'=>$msg,'data'=>$data];
}

$dsn = 'mysql:dbname=uni_curd;host=127.0.0.1';
$user = 'root';
$password = 'root';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
	exit;
}

class Server{
	public function __construct(){
		
	}
	public function index(){
		return 'index';
	}
	public function error_404(){
		return 'error_404';
	}
	public function add($data){
		global $dbh;
		extract($data);
		$sth=$dbh->prepare("insert into article(title,content) values (:title,:content)");
		$r=$sth->execute(['title'=>$title,'content'=>$content]);
		if($r){
			return todata();
		}else{
			return todata(1,'插入失败');
		}
	}
	public function mod($data){
		global $dbh;
		extract($data);
		isset($itemid) or $itemid=0;
		$itemid=intval($itemid);
		$sth=$dbh->prepare("update article set title=:title,content=:content where itemid=:itemid");
		$r=$sth->execute(['title'=>$title,'content'=>$content,'itemid'=>$itemid]);
		if($r){
			return todata();
		}else{
			return todata(1,'修改失败');
		}
	}
	public function lst($data){
		global $dbh;
		extract($data);
		isset($page) or $page=1;
		$page=intval($page);
		$pagesize=10;
		$offset=($page-1)*$pagesize;
		$sth=$dbh->prepare("select * from article where 1=1 order by itemid desc limit {$offset},{$pagesize}");
		$sth->execute();
		$result=$sth->fetchAll(PDO::FETCH_ASSOC);
		$sth=$dbh->prepare("select count(*) from article where 1=1");
		$sth->execute();
		$result2=$sth->fetch(PDO::FETCH_NUM);
		$total_page=ceil($result2[0]/$pagesize);
		return todata(0,'',['lst'=>$result,'total_page'=>$total_page,'sql'=>"select * from article where 1=1 order by itemid desc limit {$offset},{$pagesize}"]);
	}
	public function show($data){
		global $dbh;
		extract($data);
		isset($itemid) or $itemid=0;
		$itemid=intval($itemid);
		$sth=$dbh->prepare("select * from article where itemid=:itemid");
		$sth->execute(['itemid'=>$itemid]);
		$result=$sth->fetch(PDO::FETCH_ASSOC);
		if($result){
			return todata(0,'',$result);
		}else{
			return todata(1,'not found');
		}
	}
	public function del($data){
		global $dbh;
		extract($data);
		isset($itemid) or $itemid=0;
		$itemid=intval($itemid);
		$sth=$dbh->prepare("delete from article where itemid=:itemid");
		$r=$sth->execute(['itemid'=>$itemid]);
		if($r){
			return todata();
		}else{
			return todata(1,'删除失败');
		}
	}
	public function upload_image($data){
		global $dbh;
		extract($data);
		//{"name":"big_cats085.jpg","type":"image\/jpeg","tmp_name":"C:\\Users\\szh\\AppData\\Local\\Temp\\php6A7.tmp","error":0,"size":481978}
		$file=$_FILES['file'];
		if(!$file){
			return todata(1,'请选择图片文件');
		}
		if($file['error']>0){
			return todata(1,'图片上传出现错误：'.$file['error']);
		}
		if(!in_array($file['type'],['image/jpeg','image/jpg','image/png','image/gif'])){
			return todata(1,'图片文件类型不正确');
		}
		if($file['size']>300*1024){
			return todata(1,'图片大小超出300KB');
		}
		$extension=pathinfo($file['name'],PATHINFO_EXTENSION);
		$filename=md5(microtime(true).rand(10000,99999)).'.'.$extension;
		$destination='uploads/'.$filename;
		$url=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].'/'.$destination;
		if(!move_uploaded_file($file['tmp_name'],$destination)){
			return todata(1,'图片保存失败');
		}
		return todata(0,'upload success',['url'=>$url]);
	}
	public function login($data){
		global $dbh;
		extract($data);
		
		isset($username) or $username='';
		$username=trim($username);
		isset($password) or $password='';
		$password=trim($password);
		if(!$username || !$password){
			return todata(1,'账号密码不能为空');
		}
		$sth=$dbh->prepare("select * from member where username=:username");
		$sth->execute(['username'=>$username]);
		$result=$sth->fetch(PDO::FETCH_ASSOC);
		if(!$result){
			return todata(1,'账号不存在');
		}
		if(md5($password)!=$result['password']){
			return todata(1,'密码不正确');
		}
		unset($result['password']);
		return todata(0,'登录成功',$result);
	}
}

isset($_GET['action']) or $_GET['action']='index';
$action=$_GET['action'];
$server=new Server();
if(method_exists($server,$action) and !in_array($action,['__construct','__destruct'])){
	echo json_encode($server->$action(array_merge($_GET,$_POST)));
}else{
	echo $server->error_404();
}

